import { crawlAllVideoDetails, crawlVideoDetails, crawlVideoTypes } from './crawler-service';
import { crawlBanners } from './banner-crawler-service';

// 任务类型枚举
export enum CrawlerType {
  CRAWL_VIDEO_TYPES = 'CRAWL_VIDEO_TYPES',
  CRAWL_VIDEO_DETAILS = 'CRAWL_VIDEO_DETAILS',
  CRAWL_ALL_VIDEO_DETAILS = 'CRAWL_ALL_VIDEO_DETAILS',
  CRAWL_BANNERS = 'CRAWL_BANNERS',
  CRAWL_BANNERS_AND_RECENT_VIDEOS = 'CRAWL_BANNERS_AND_RECENT_VIDEOS',
}

// 爬虫参数接口
export interface CrawlerParams {
  page?: number;
  limit?: number;
  maxPages?: number;
  startPage?: number;
  pageLimit?: number;
  hours?: number;
}

// 爬虫结果接口
export interface CrawlerResult {
  success: boolean;
  data?: unknown;
  error?: string;
  message?: string;
}

/**
 * 执行视频类型爬取
 */
export async function executeVideoTypesCrawler(): Promise<CrawlerResult> {
  try {
    console.log('开始采集视频类型...');
    const videoTypes = await crawlVideoTypes();
    return {
      success: true,
      data: videoTypes,
      message: `成功采集 ${videoTypes.length} 个视频类型`,
    };
  } catch (error) {
    console.error('采集视频类型失败:', error);
    return {
      success: false,
      error: String(error),
      message: '采集视频类型失败',
    };
  }
}

/**
 * 执行视频详情爬取
 */
export async function executeVideoDetailsCrawler(
  page: number = 1,
  limit: number = 20, 
  hours?: number
): Promise<CrawlerResult> {
  try {
    console.log(`开始采集视频详情... (页码: ${page}, 每页: ${limit}${hours ? `, 最近${hours}小时` : ''})`);
    const videos = await crawlVideoDetails(page, limit, hours);
    return {
      success: true,
      data: videos,
      message: `成功采集 ${videos.length} 个视频详情`,
    };
  } catch (error) {
    console.error('采集视频详情失败:', error);
    return {
      success: false,
      error: String(error),
      message: '采集视频详情失败',
    };
  }
}

/**
 * 执行所有视频详情爬取
 */
export async function executeAllVideoDetailsCrawler(
  startPage: number = 1,
  pageLimit: number = 20,
  maxPages?: number,
  hours?: number
): Promise<CrawlerResult> {
  try {
    console.log(`开始分页采集所有视频详情... (起始页: ${startPage}, 每页: ${pageLimit}${maxPages ? `, 最大页数: ${maxPages}` : ''}${hours ? `, 最近${hours}小时` : ''})`);
    const allVideos = await crawlAllVideoDetails(startPage, pageLimit, maxPages, hours);
    return {
      success: true,
      data: allVideos,
      message: `成功采集所有视频详情，共 ${allVideos.totalCount} 个视频，${allVideos.pages} 页`,
    };
  } catch (error) {
    console.error('采集所有视频详情失败:', error);
    return {
      success: false,
      error: String(error),
      message: '采集所有视频详情失败',
    };
  }
}

/**
 * 执行轮播图爬取
 */
export async function executeBannersCrawler(): Promise<CrawlerResult> {
  try {
    console.log('开始采集轮播图数据...');
    const banners = await crawlBanners();
    return {
      success: true,
      data: banners,
      message: `成功采集 ${banners.length} 个轮播图`,
    };
  } catch (error) {
    console.error('采集轮播图失败:', error);
    return {
      success: false,
      error: String(error),
      message: '采集轮播图失败',
    };
  }
}

/**
 * 执行轮播图和最近视频并行爬取
 */
export async function executeBannersAndRecentVideosCrawler(hours: number = 2): Promise<CrawlerResult> {
  try {
    console.log(`开始并行采集轮播图和最近${hours}小时视频...`);
    // 并行执行两个采集任务
    const [parallelBanners, allVideos] = await Promise.all([
      crawlBanners().catch(error => {
        console.error('采集轮播图出错:', error);
        return [];
      }),
      crawlAllVideoDetails(1, 20, Infinity, hours)
    ]);

    return {
      success: true,
      data: {
        banners: parallelBanners,
        videos: allVideos.totalCount
      },
      message: `并行采集完成：${parallelBanners.length} 个轮播图，${allVideos.totalCount} 个最近视频`,
    };
  } catch (error) {
    console.error('并行采集失败:', error);
    return {
      success: false,
      error: String(error),
      message: '并行采集轮播图和最近视频失败',
    };
  }
}

/**
 * 根据类型执行爬虫
 */
export async function executeCrawler(
  type: CrawlerType,
  params: CrawlerParams = {}
): Promise<CrawlerResult> {
  try {
    switch (type) {
      case CrawlerType.CRAWL_VIDEO_TYPES:
        return await executeVideoTypesCrawler();

      case CrawlerType.CRAWL_VIDEO_DETAILS:
        const { page = 1, limit = 20, hours: detailsHours } = params;
        return await executeVideoDetailsCrawler(page, limit, detailsHours);

      case CrawlerType.CRAWL_ALL_VIDEO_DETAILS:
        const { startPage = 1, pageLimit = 20, maxPages, hours: allHours } = params;
        return await executeAllVideoDetailsCrawler(startPage, pageLimit, maxPages, allHours);

      case CrawlerType.CRAWL_BANNERS:
        return await executeBannersCrawler();

      case CrawlerType.CRAWL_BANNERS_AND_RECENT_VIDEOS:
        return await executeBannersAndRecentVideosCrawler(params.hours);

      default:
        throw new Error(`未知的爬虫类型: ${type}`);
    }
  } catch (error) {
    console.error(`执行爬虫失败 (${type}):`, error);
    return {
      success: false,
      error: String(error),
      message: `执行爬虫失败: ${error}`,
    };
  }
} 